/*
 * by cansik / Florian
 * Datum: 06.05.2010
 * Zeit: 15:57
 * 
 *
 */
using System;
using System.Collections.Generic;
using System.Drawing;

namespace PixelReplacer
{
	/// <summary>
	/// VektorRecogniser trys to recognize the filtered pixels
	/// </summary>
	public class VektorRecogniser : Replacer
	{
        /// <summary>
        /// List of RulePoints
        /// </summary>
		public List<RulePoint> VektorPoints{get; set;}
        /// <summary>
        /// Just the filtered Pixels on a transparent Image
        /// </summary>
		public Bitmap Overlay{get; private set;}

        /// <summary>
        /// Indicates if the real color will be shown!
        /// </summary>
        public Boolean RealColor { get; set; }
		
        /// <summary>
        /// Initialize a new Vector Recogniser
        /// </summary>
		public VektorRecogniser()
		{
			Rules = new List<PixelRule>();
			VektorPoints = new List<RulePoint>();
		}
		
        /// <summary>
        /// Handler does just save the rule and position of the Point (no mixing or replacing)
        /// </summary>
        /// <param name="c">Color of the pixel</param>
        /// <param name="x">X coordinate of the Pixel</param>
        /// <param name="y">Y coordinate of the Pixel</param> 
        /// <param name="rule">Matching Rule</param>
        /// <returns>Calculated Color</returns>
		protected override Color Handler(Color c, int x, int y, PixelRule rule)
		{
			VektorPoints.Add(new RulePoint(new Point(x, y), rule, c));
            return c;
		}
		
        /// <summary>
        /// Creates a bitmap from the matching pixels on the original image
        /// </summary>
		public override void Recognize()
		{
			Overlay = new Bitmap(this.Picture.Width, this.Picture.Height);
			base.Recognize();
			this.Overlay = CreateVektorImage(this.Overlay, VektorPoints.ToArray());
            this.Picture = (Bitmap)this.Overlay.Clone(); //MayBe Not Good
		}
		
        /// <summary>
        /// Creates a new Image from the Old Picture onto a new one
        /// </summary>
        /// <param name="pic">New Picture</param>
        /// <param name="points">Matching Points</param>
        /// <returns>Image with just the matching points</returns>
		private Bitmap CreateVektorImage(Bitmap pic, RulePoint[] points)
		{
			Graphics g = Graphics.FromImage(pic);
            g.Clear(Color.Transparent); //(Color.Black);
			g.Save();
			
			foreach(RulePoint p in points)
			{
                //maybe should be faster! (unsafe)
                if (RealColor)
                {
                    pic.SetPixel(p.Coordinates.X, p.Coordinates.Y, p.OriginalColor);
                }
                else
                {
                    pic.SetPixel(p.Coordinates.X, p.Coordinates.Y, p.Rule.NewColor);
                }
			}
			
			return pic;
		}
	}
}
